import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mesh/function/widgets/toast_widget.dart';

import '../../function/states/user_state.dart';
import '../../function/states/post_state.dart';
import '../../function/states/follow_state.dart';
import '../../function/models/user_data_model.dart';
import '../../function/models/post_model.dart';
import '../../function/widgets/animated_tap_widget.dart';
import '../../function/widgets/login_dialog.dart';
import '../../function/widgets/report_dialog.dart';
import '../../function/routes/app_route_manager.dart';

/// 他人中心页面
class OtherUserCenterScreen extends StatefulWidget {
  final String targetUserId; // 目标用户ID

  const OtherUserCenterScreen({super.key, required this.targetUserId});

  @override
  State<OtherUserCenterScreen> createState() => _OtherUserCenterScreenState();
}

class _OtherUserCenterScreenState extends State<OtherUserCenterScreen> {
  late PageController _pageController;
  int _currentTabIndex = 0;

  // 用户数据
  UserDataModel? _targetUser;
  List<PostModel> _userPosts = [];
  List<PostModel> _userFavorites = [];

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: _currentTabIndex);
    _loadUserData();

    // 监听关注状态变化
    FollowState.userFollowsMapBeacon.subscribe((followsMap) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  /// 加载用户数据
  void _loadUserData() {
    _targetUser = UserState.queryUserById(widget.targetUserId);
    if (_targetUser != null) {
      _loadUserPosts();
      _loadUserFavorites();
    }
  }

  /// 加载用户发布的动态
  void _loadUserPosts() {
    _userPosts = PostState.getPostsByUserId(widget.targetUserId);
  }

  /// 加载用户收藏的动态
  void _loadUserFavorites() {
    _userFavorites = PostState.getUserFavoritePosts(widget.targetUserId);
  }

  @override
  Widget build(BuildContext context) {
    if (_targetUser == null) {
      return Scaffold(
        body: Container(
          width: double.infinity,
          height: double.infinity,
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/common_bg.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: SafeArea(
            child: Center(
              child: Text('User not found')
                  .fontSize(16.sp)
                  .textColor(Colors.white)
                  .fontWeight(FontWeight.w500)
                  .fontFamily(
                    GoogleFonts.quicksand(
                      fontWeight: FontWeight.w500,
                    ).fontFamily,
                  ),
            ),
          ),
        ),
      );
    }

    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏（固定）
              _buildTopNavigationBar(),

              // 可滚动的内容区域
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      // 用户信息区域
                      _buildUserInfoSection(),

                      SizedBox(height: 20.h),

                      // 标签页
                      _buildTabBar(),

                      SizedBox(height: 16.h),

                      // 内容区域
                      _buildContentSection(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          AnimatedTapWidget(
            onTap: () => AppRouteManager.goBack(),
            child: Icon(Icons.chevron_left, color: Colors.white, size: 24.w),
          ),

          SizedBox(width: 16.w),

          // 标题
          Expanded(
            child: Text("${_targetUser?.userName ?? 'User'}'s Personal Center")
                .fontSize(18.sp)
                .textColor(Colors.white)
                .fontWeight(FontWeight.w600)
                .fontFamily(
                  GoogleFonts.quicksand(fontWeight: FontWeight.w600).fontFamily,
                ),
          ),

          // 举报按钮
          AnimatedTapWidget(
            onTap: () => _showUserReportDialog(),
            child: Image.asset(
              'assets/images/report.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建用户信息区域
  Widget _buildUserInfoSection() {
    return Container(
      padding: EdgeInsets.all(20.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户头像
          Container(
            width: 64.w,
            height: 64.w,
            decoration: BoxDecoration(shape: BoxShape.circle),
            child: ClipOval(
              child: Image.asset(_targetUser!.avatar, fit: BoxFit.cover),
            ),
          ),

          SizedBox(width: 16.w),

          // 用户信息和统计数据
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 用户名
                Text(_targetUser!.userName)
                    .fontSize(18.sp)
                    .textColor(Colors.white)
                    .fontWeight(FontWeight.w700)
                    .fontFamily(
                      GoogleFonts.quicksand(
                        fontWeight: FontWeight.w700,
                      ).fontFamily,
                    )
                    .paddingLeft(6.w),

                SizedBox(height: 16.h),

                // 统计信息
                _buildStatsSection(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建统计信息区域
  Widget _buildStatsSection() {
    final followCount = FollowState.getFollowCount(_targetUser!.userId);
    final followerCount = FollowState.getFollowerCount(_targetUser!.userId);

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        _buildStatItem('$followCount', 'Follow'),
        _buildStatItem('$followerCount', 'Following'),
        _buildStatItem('24', 'Visitor'), // 暂时硬编码访客数
      ],
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String label, String value) {
    return Column(
      children: [
        Text(label)
            .fontSize(16.sp)
            .textColor(Colors.white)
            .fontWeight(FontWeight.w700)
            .fontFamily(
              GoogleFonts.quicksand(fontWeight: FontWeight.w700).fontFamily,
            ),

        SizedBox(height: 4.h),
        Text(value)
            .fontSize(13.sp)
            .textColor(Colors.white)
            .fontWeight(FontWeight.w400)
            .fontFamily(
              GoogleFonts.quicksand(fontWeight: FontWeight.w400).fontFamily,
            ),
      ],
    );
  }

  /// 构建标签栏
  Widget _buildTabBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children: [
          // 第一个Tab - 靠左对齐
          GestureDetector(
            onTap: () {
              setState(() => _currentTabIndex = 0);
              _pageController.animateToPage(
                0,
                duration: Duration(milliseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            child: Text('The Updates They Posted')
                .fontSize(16.sp)
                .textColor(
                  _currentTabIndex == 0
                      ? Colors.white
                      : Colors.white.withOpacity(0.7),
                )
                .fontFamily(
                  GoogleFonts.quicksand(fontWeight: FontWeight.w700).fontFamily,
                )
                .fontWeight(FontWeight.w700)
                .textAlignment(TextAlign.center),
          ),
          SizedBox(width: 20.w),
          // 第二个Tab - 靠左对齐
          GestureDetector(
            onTap: () {
              setState(() => _currentTabIndex = 1);
              _pageController.animateToPage(
                1,
                duration: Duration(milliseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            child: Text('Like')
                .fontSize(16.sp)
                .textColor(
                  _currentTabIndex == 1
                      ? Colors.white
                      : Colors.white.withOpacity(0.7),
                )
                .fontFamily(
                  GoogleFonts.quicksand(fontWeight: FontWeight.w700).fontFamily,
                )
                .fontWeight(FontWeight.w700)
                .textAlignment(TextAlign.center),
          ),
          // 占位空间，让Tab靠左
          Spacer(),
        ],
      ),
    );
  }

  /// 构建内容区域
  Widget _buildContentSection() {
    // 计算内容高度，确保PageView有足够的高度显示内容
    final maxPostsCount = [
      _userPosts.length,
      _userFavorites.length,
    ].reduce((a, b) => a > b ? a : b);
    final contentHeight = maxPostsCount > 0 ? maxPostsCount * 320.h : 400.h;

    return SizedBox(
      height: contentHeight,
      child: PageView(
        controller: _pageController,
        onPageChanged: (index) {
          setState(() {
            _currentTabIndex = index;
          });
        },
        children: [
          _buildTabContent(0), // 发布的动态
          _buildTabContent(1), // 收藏的动态
        ],
      ),
    );
  }

  /// 构建标签页内容
  Widget _buildTabContent(int tabIndex) {
    final posts = tabIndex == 0 ? _userPosts : _userFavorites;

    if (posts.isEmpty) {
      return _buildEmptyState();
    }

    return Column(
      children: [
        for (int index = 0; index < posts.length; index++)
          _buildPostCard(posts[index], tabIndex),
      ],
    ).paddingHorizontal(16.w);
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset('assets/images/empty.png', width: 120.w, height: 120.w),
          SizedBox(height: 20.h),
          Text(_currentTabIndex == 0 ? 'No posts yet' : 'No favorites yet')
              .fontSize(16.sp)
              .textColor(Colors.white.withOpacity(0.6))
              .fontWeight(FontWeight.w400)
              .fontFamily(
                GoogleFonts.quicksand(fontWeight: FontWeight.w400).fontFamily,
              ),
        ],
      ),
    );
  }

  /// 构建动态卡片
  Widget _buildPostCard(PostModel post, int tabIndex) {
    final userInfo = PostState.getUserInfo(post.userId);
    final userName = userInfo?['userName'] ?? 'Guest';
    final userAvatar = userInfo?['userAvatar'] ?? 'assets/images/avatar1.png';

    // 获取当前登录用户信息
    final currentUser = UserState.getCurrentUserInfo();
    final isLoggedIn = UserState.checkLoginStatus();
    final currentUserId = currentUser?.userId ?? '';

    // 检查是否已关注该用户
    final isFollowing = FollowState.isFollowing(currentUserId, post.userId);

    // 检查是否已收藏该动态
    final isFavorited = PostState.isPostFavorited(currentUserId, post.postId);

    // 判断是否为用户自己的动态
    final isOwnPost = currentUserId == post.userId;

    return GestureDetector(
      onTap: () => AppRouteManager.navigateToPostDetail(post.postId),
      child: Container(
        margin: EdgeInsets.only(bottom: 20.h),
        child: AspectRatio(
          aspectRatio: 343 / 274,
          child: Container(
            decoration: BoxDecoration(
              color: const Color(0xFF663507),
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 用户信息头部
                  Row(
                    children: [
                      // 用户头像
                      ClipOval(
                        child: Image.asset(
                          userAvatar,
                          width: 40.w,
                          height: 40.w,
                          fit: BoxFit.cover,
                        ),
                      ),
                      SizedBox(width: 12.w),
                      // 用户名和时间
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(userName)
                                .fontSize(16.sp)
                                .textColor(Colors.white)
                                .fontWeight(FontWeight.w800)
                                .fontFamily(
                                  GoogleFonts.quicksand(
                                    fontWeight: FontWeight.w800,
                                  ).fontFamily,
                                ),
                            Text(_formatTime(post.publishTime))
                                .fontSize(12.sp)
                                .textColor(Colors.white)
                                .fontFamily(
                                  GoogleFonts.quicksand(
                                    fontWeight: FontWeight.w600,
                                  ).fontFamily,
                                ),
                          ],
                        ),
                      ),
                      // 关注按钮
                      if (!isOwnPost) ...[
                        GestureDetector(
                          onTap: () {
                            if (!isLoggedIn) {
                              LoginDialog.show(context);
                              return;
                            }

                            // 切换关注状态
                            FollowState.toggleFollow(
                              currentUserId,
                              post.userId,
                            );
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 12.w,
                              vertical: 6.h,
                            ),
                            decoration: BoxDecoration(
                              color:
                                  isFollowing
                                      ? const Color(0xFF854914)
                                      : Colors.white,
                              borderRadius: BorderRadius.circular(32.r),
                              border: Border.all(
                                color:
                                    isFollowing
                                        ? const Color(0xFF854914)
                                        : Colors.white,
                                width: 1.w,
                              ),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Image.asset(
                                  isFollowing
                                      ? 'assets/images/unfollow.png'
                                      : 'assets/images/follow.png',
                                  width: 14.w,
                                  height: 14.w,
                                  color:
                                      isFollowing
                                          ? Colors.white
                                          : const Color(0xFFFF8A3C),
                                ),
                                SizedBox(width: 4.w),
                                Text(
                                  isFollowing ? 'Unfollow' : 'Follow',
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    color:
                                        isFollowing
                                            ? Colors.white
                                            : const Color(0xFFFF8A3C),
                                    fontFamily:
                                        GoogleFonts.quicksand(
                                          fontWeight: FontWeight.w600,
                                        ).fontFamily,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ],
                  ),

                  SizedBox(height: 12.h),

                  // 动态内容
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 文字内容
                        Text(
                              post.content.length > 100
                                  ? '${post.content.substring(0, 100)}...'
                                  : post.content,
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            )
                            .fontSize(12.sp)
                            .fontFamily(
                              GoogleFonts.quicksand(
                                fontWeight: FontWeight.w700,
                              ).fontFamily,
                            )
                            .textColor(Colors.white)
                            .textAlignment(TextAlign.left),

                        SizedBox(height: 8.h),

                        // 媒体画廊（图片和视频缩略图）
                        if (post.mediaUrls.isNotEmpty)
                          Expanded(
                            child: Container(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10.r),
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(10.r),
                                child: Row(
                                  children: [
                                    // 固定显示3个位置
                                    for (int i = 0; i < 3; i++) ...[
                                      Expanded(
                                        child: Container(
                                          margin: EdgeInsets.only(right: 4.w),
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(
                                              8.r,
                                            ),
                                            color:
                                                i < post.mediaUrls.length
                                                    ? null
                                                    : Colors.transparent,
                                            image:
                                                i < post.mediaUrls.length
                                                    ? DecorationImage(
                                                      image: AssetImage(
                                                        post.isVideoAtIndex(
                                                                  i,
                                                                ) &&
                                                                post.getVideoThumbnailAtIndex(
                                                                      i,
                                                                    ) !=
                                                                    null
                                                            ? post
                                                                .getVideoThumbnailAtIndex(
                                                                  i,
                                                                )!
                                                            : post.mediaUrls[i],
                                                      ),
                                                      fit: BoxFit.cover,
                                                    )
                                                    : null,
                                          ),
                                          child:
                                              i < post.mediaUrls.length &&
                                                      post.isVideoAtIndex(i)
                                                  ? Stack(
                                                    children: [
                                                      Center(
                                                        child: Image.asset(
                                                          'assets/images/play.png',
                                                          width: 24.w,
                                                          height: 24.w,
                                                        ),
                                                      ),
                                                    ],
                                                  )
                                                  : null,
                                        ),
                                      ),
                                    ],
                                  ],
                                ),
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),

                  SizedBox(height: 8.h),

                  // 底部操作栏
                  Container(
                    width: double.infinity,
                    height: 44.h,
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    decoration: ShapeDecoration(
                      color: const Color(0xFF854914),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(14.r),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // 点赞和评论
                        Row(
                          children: [
                            GestureDetector(
                              onTap: () {
                                if (!isLoggedIn) {
                                  LoginDialog.show(context);
                                  return;
                                }

                                // 切换收藏状态
                                PostState.togglePostFavorite(
                                  currentUserId,
                                  post.postId,
                                );
                                setState(() {});
                              },
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Image.asset(
                                    isFavorited
                                        ? 'assets/images/like-fill.png'
                                        : 'assets/images/like.png',
                                    width: 20.w,
                                    height: 20.w,
                                  ),
                                  SizedBox(width: 4.w),
                                  Text('${post.favoriteCount}')
                                      .fontSize(14.sp)
                                      .textColor(Colors.white)
                                      .fontFamily(
                                        GoogleFonts.quicksand(
                                          fontWeight: FontWeight.w600,
                                        ).fontFamily,
                                      ),
                                ],
                              ),
                            ),
                            SizedBox(width: 16.w),
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Image.asset(
                                  'assets/images/comment.png',
                                  width: 20.w,
                                  height: 20.w,
                                ),
                                SizedBox(width: 4.w),
                                Text('${post.commentCount}')
                                    .fontSize(14.sp)
                                    .textColor(Colors.white)
                                    .fontFamily(
                                      GoogleFonts.quicksand(
                                        fontWeight: FontWeight.w600,
                                      ).fontFamily,
                                    ),
                              ],
                            ),
                          ],
                        ),
                        // 举报按钮
                        GestureDetector(
                          onTap: () => _showReportDialog(post),
                          child: Image.asset(
                            'assets/images/report.png',
                            width: 20.w,
                            height: 20.w,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 显示用户举报对话框
  void _showUserReportDialog() {
    ReportDialog.show(
      context,
      onReportSuccess: () {
        // 提示
        ToastWidget.showSuccess('Report submitted successfully.');
        // 举报成功后显示提示并返回上一页
        AppRouteManager.goBack();
      },
    );
  }

  /// 显示动态举报对话框
  void _showReportDialog(PostModel post) {
    ReportDialog.show(
      context,
      onReportSuccess: () {
        // 举报成功后删除动态
        PostState.removePost(post.postId);
        setState(() {
          // 刷新数据
          _loadUserPosts();
          _loadUserFavorites();
        });
      },
    );
  }

  /// 格式化时间
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inDays > 0) {
      return '${difference.inDays}d ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}h ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}m ago';
    } else {
      return 'Just now';
    }
  }
}
